import time
from queue import Queue
from threading import Thread

import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))

class MqttUtils:
    recv_que = Queue()
    
    def __init__(self, topic,HOST="114.116.46.246", PORT=61613):
        self.topic = topic
        self.client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        self.client = mqtt.Client(self.client_id)  # ClientId不能重复，所以使用当前时间
        self.client.username_pw_set("admin", "CftM+Uod58rxjoL")  # 必须设置，否则会返回「Connected with result code 4」
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect(HOST, PORT, 60)
        self.client.publish(topic='chart',payload='Hello,EMQ!',qos=0)
        
    def run(self):
        self.client.loop_forever()
    
    def publish_msg(self,  msg):
        self.client.publish(topic="chart", payload="asdasdaa",qos=0)
    
    def get_msg(self):
        while True:
            time.sleep(1)
            if self.recv_que.qsize() > 0:
                yield self.recv_que.get()
            yield None
    
    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code " + str(rc))
        client.subscribe("chart")
    
    def on_message(self, client, userdata, msg):
        self.recv_que.put(msg.payload.decode("utf-8"))
        print(msg.topic + " " + msg.payload.decode("utf-8"))

def publih_msg(topic,msg):
    publish.single(topic=topic, payload=msg, qos=0, hostname="114.116.46.246", port=61613, client_id=client_id,
               auth={'username': "admin", 'password': "CftM+Uod58rxjoL"})
    
if __name__ == '__main__':
    #mqtt = MqttUtils(topic="chart")
    publih_msg("chart","saad")
    # mqtt.publish_msg("asd")
    # t1 = Thread(target=mqtt.run())
    # t1.start()
    #
    # for mqtt_msg in mqtt.get_msg():
    #     print(mqtt)
    # client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # publish.single("chart", "你好 MQTT", qos=1, hostname="127.0.0.1", port=61613, client_id=client_id,
    #                auth={'username': "admin", 'password': "password"})